package org.asiainfo.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import org.asiainfo.common.core.constant.CacheConstants;
import org.asiainfo.common.core.domain.R;
import org.asiainfo.common.core.utils.StreamUtils;
import org.asiainfo.common.core.utils.StringUtils;
import org.asiainfo.common.log.annotation.Log;
import org.asiainfo.common.log.enums.BusinessType;
import org.asiainfo.common.mybatis.stream.core.page.TableDataInfo;
import org.asiainfo.common.redis.utils.RedisUtils;
import org.asiainfo.common.web.core.BaseController;
import org.asiainfo.system.api.domain.SysUserOnline;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

/**
 * 在线用户监控
 *
 * @author dotor-ww
 */
@RestController
@RequestMapping("/online")
@RequiredArgsConstructor
public class SysUserOnlineController extends BaseController {

    /**
     * 获取在线用户列表
     *
     * @param userName 用户名
     * @return 在线用户
     */
    @SaCheckPermission("system:online:list")
    @GetMapping("/list")
    public TableDataInfo<SysUserOnline> list(String userName) {
        // 基于satoken拿取redis缓存用户数据
        List<String> keys = StpUtil.searchTokenValue("", 0, -1, false);
        List<SysUserOnline> userOnlineList = CollUtil.newArrayList();
        for (String key : keys) {
            String token = StringUtils.substringAfterLast(key, ":");
            // 排除过期token及当前用户自身登录的token
            if (StpUtil.stpLogic.getTokenActiveTimeoutByToken(token) < -1 || StpUtil.getTokenSession().getToken().equals(token)) {
                continue;
            }
            userOnlineList.add(RedisUtils.getCacheObject(CacheConstants.ONLINE_TOKEN_KEY + token));
        }
        if (StringUtils.isNotEmpty(userName)) {
            userOnlineList = StreamUtils.filter(userOnlineList, userOnline -> StringUtils.equals(userName, userOnline.getUserName()));
        }
        Collections.reverse(userOnlineList);
        userOnlineList.removeAll(Collections.singleton(null));
        List<SysUserOnline> sysUserOnlineList = BeanUtil.copyToList(userOnlineList, SysUserOnline.class);
        return TableDataInfo.build(sysUserOnlineList);
    }

    /**
     * 强制下线
     *
     * @param tokenId 用户tokenId
     * @return 结果
     */
    @SaCheckPermission("system:online:forceLogout")
    @Log(title = "在线用户", businessType = BusinessType.FORCE)
    @DeleteMapping("/{tokenId}")
    public R<Void> forceLogout(@PathVariable String tokenId) {
        try {
            StpUtil.kickoutByTokenValue(tokenId);
        } catch (NotLoginException ignored) {
        }
        return R.ok();
    }
}
